package com.bootdo.appsystem.controller;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bootdo.app.utils.MyMath;
import com.bootdo.appsystem.domain.ShouruDO;
import com.bootdo.appsystem.domain.UsershouruDO;
import com.bootdo.appsystem.service.ShouruService;
import com.bootdo.appsystem.service.UseraccountService;
import com.bootdo.appsystem.service.UsershouruService;
import com.bootdo.appsystem.utils.ExcelExportUtil4DIY;
import com.bootdo.common.annotation.Log;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.appsystem.domain.TixianDO;
import com.bootdo.appsystem.service.TixianService;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2018-07-28 14:55:18
 */

@Controller
@RequestMapping("/appsystem/tixian")
public class TixianController {

    private static Logger logger = LoggerFactory.getLogger(TixianController.class);

    @Autowired
    private TixianService tixianService;
    @Autowired
    private UseraccountService useraccountService;
    @Autowired
    private ShouruService shouruService;
    @Autowired
    private UsershouruService usershouruService;

    @GetMapping()
    @RequiresPermissions("appsystem:tixian:tixian")
    String Tixian() {
        return "appsystem/tixian/tixian";
    }

    @GetMapping("/shenheList")
    @RequiresPermissions("appsystem:tixian:shenhe")
    String shenheTixian() {
        return "appsystem/tixian/shenhetixian";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("appsystem:tixian:tixian")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        String uid = (String) params.get("uid");
        if (uid.equals("-10000")) {
            params.remove("uid");
        }
        Query query = new Query(params);
        List<TixianDO> tixianList = tixianService.list(query);
        int total = tixianService.count(query);
        PageUtils pageUtils = new PageUtils(tixianList, total);
        return pageUtils;
    }

    @ResponseBody
    @GetMapping("/shenheMsgList")
    @RequiresPermissions("appsystem:tixian:shenhe")
    public PageUtils shenheList(@RequestParam Map<String, Object> params) {
        //查询列表数据
        String uid = (String) params.get("uid");
        if (uid.equals("-10000")) {
            params.remove("uid");
        }
        params.put("status", "0");
        Query query = new Query(params);
        List<TixianDO> tixianList = tixianService.list(query);
        int total = tixianService.count(query);
        PageUtils pageUtils = new PageUtils(tixianList, total);
        return pageUtils;
    }


    @GetMapping("/add")
    @RequiresPermissions("appsystem:tixian:add")
    String add() {
        return "appsystem/tixian/add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("appsystem:tixian:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        TixianDO tixian = tixianService.get(id);
        model.addAttribute("tixian", tixian);
        return "appsystem/tixian/edit";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("appsystem:tixian:add")
    public R save(TixianDO tixian) {
        if (tixianService.save(tixian) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("appsystem:tixian:edit")
    public R update(TixianDO tixian) {
        tixian.setEdittime(new Date());
        tixianService.update(tixian);
        return R.ok();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/shenhe")
    @RequiresPermissions("appsystem:tixian:edit")
    public R shenhe(Integer i, Integer id) {
        try {
            if (i == 100000) {
                //审核通过
                TixianDO tixianDO = new TixianDO();
                tixianDO.setEdittime(new Date());
                tixianDO.setId(id);
                tixianDO.setStatus(1);
                tixianService.update(tixianDO);
            } else if (i == 200000) {
                TixianDO tixian = tixianService.get(id);
                //审核不通过
                TixianDO tixianDO = new TixianDO();
                tixianDO.setEdittime(new Date());
                tixianDO.setId(id);
                tixianDO.setStatus(-1);
                tixianService.update(tixianDO);

                //给用户余额中加钱
                useraccountService.addMoneyNotAll(tixian.getUid(), tixian.getMoney());

                //用户收入表中记录数据
                ShouruDO shouruDO = new ShouruDO().notTixianShouru(tixian.getUid(), tixian.getMoney());
                shouruService.save(shouruDO);

                //todo 用户收支表中记录数据? 没有保存吗？
                UsershouruDO usershouru = usershouruService.getByUid(tixian.getUid());
                usershouru.setTixian(MyMath.add(usershouru.getTixian(), tixian.getMoney()));
            }
            return R.ok();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return R.error();
        }
    }


    /**
     * 批量修改用户提现成功
     * @param ids
     * @return
     */
    @Log("批量审核通过提现审核")
    @PostMapping("/batchUpdate")
    @ResponseBody
    @RequiresPermissions("appsystem:tixian:batchUpdate")
    public R update(@RequestParam("ids[]") Integer[] ids) {
        tixianService.batchUpdate(ids);
        return R.ok();
    }


    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("appsystem:tixian:remove")
    public R remove(Integer id) {
        if (tixianService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("appsystem:tixian:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        tixianService.batchRemove(ids);
        return R.ok();
    }


    /**
     * 导出Excel表
     * @param params
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value="/exportExcel")
    public void exportExcel(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String filename = "提现数据"+format.format(new Date().getTime())+".xls";
        response.setContentType("application/ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes(),"iso-8859-1"));
        OutputStream out = response.getOutputStream();
        try {
            String uid = (String) params.get("uid");
            if(uid != null){
                if (uid.equals("-10000")) {
                    params.remove("uid");
                }
            }
            params.put("status", "0");
            Query query = new Query(params);
            String type = request.getParameter("type");
            // 导出当前页面数据
            if(type.equals("1")){
                List<TixianDO> list = tixianService.list(query);
                ExcelExportUtil4DIY.exportToFile(list,out);
            }
            //导出全部数据
            if(type.equals("2")){
                List<TixianDO> list = tixianService.list(null);
                ExcelExportUtil4DIY.exportToFile(list,out);
            }
            //导出符合条件的全部数据
            if(type.equals("3")){
                query.remove("offset");
                query.remove("limit");
                List<TixianDO> list = tixianService.list(query);
                ExcelExportUtil4DIY.exportToFile(list,out);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("exportExcel出错"+e.getMessage());
        }finally{
            out.close();
        }
    }
















}
